#!/usr/bin/env python

# Plugin called by xapi whenever an external_auth_type is enabled or disabled as an 
# Also when a subject is added or removed.

import XenAPIPlugin

def get_extauth_handler(args):
    # Return an object that can handle the external_auth_type use by Host
    auth_type = args['auth_type']
    try:
        return __import__('extauth-hook-%s' % auth_type)
    except:
        return None

def after_extauth_enable(session, args):
    hdlr = get_extauth_handler(args)
    if hdlr:
        return hdlr.after_extauth_enable(session, args)
    return str(True)

def after_xapi_initialize(session, args):
    hdlr = get_extauth_handler(args)
    if hdlr:
        return hdlr.after_xapi_initialize(session, args)
    return str(True)

def after_subject_add(session, args):
    hdlr = get_extauth_handler(args)
    if hdlr:
        return hdlr.after_subject_add(session, args)
    return str(True)

def after_subject_remove(session, args):
    hdlr = get_extauth_handler(args)
    if hdlr:
        return hdlr.after_subject_remove(session, args)
    return str(True)

def after_roles_update(session, args):
    hdlr = get_extauth_handler(args)
    if hdlr:
        return hdlr.after_roles_update(session, args)
    return str(True)

def before_extauth_disable(session, args):
    hdlr = get_extauth_handler(args)
    if hdlr:
        return hdlr.before_extauth_disable(session, args)
    return str(True)


# The dispatcher
if __name__ == "__main__":
    dispatch_tbl = {
        "after-extauth-enable":  after_extauth_enable,
        "after-xapi-initialize": after_xapi_initialize, 
        "after-subject-add":     after_subject_add, 
        "after-subject-remove":  after_subject_remove, 
        "after-roles-update":    after_roles_update, 
        "before-extauth-disable":before_extauth_disable,
    }
    XenAPIPlugin.dispatch(dispatch_tbl)

